#!/bin/bash

# SeaLogWiki 一键安装器
# 支持指定版本和默认latest版本，一键安装启动和一键卸载

set -e

# 信号处理 - 优雅退出
cleanup_on_exit() {
    local exit_code=$?
    if [ $exit_code -ne 0 ]; then
com        log_error "脚本异常退出 (退出码: $exit_code)"
    fi
}

trap cleanup_on_exit EXIT
trap 'log_warn "收到中断信号，正在清理..."; exit 130' INT TERM

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# 配置变量
SCRIPT_VERSION="1.0.0"
DEFAULT_VERSION="latest"
DOCKER_REGISTRY="swr.cn-east-3.myhuaweicloud.com/cloud-mdgx/sealog"  # 华为云容器镜像服务
GITEE_BASE_URL="https://gitee.com/metastone-project/SealogWiki"
PROJECT_NAME="sealogwiki"
INSTALL_DIR="${HOME}/.sealogwiki"
COMPOSE_FILE="$INSTALL_DIR/docker-compose.yml"
ENV_FILE="$INSTALL_DIR/.env"

# 显示横幅
show_banner() {
    echo -e "${CYAN}"
    echo "=================================================="
    echo "    SeaLogWiki 一键安装器 v${SCRIPT_VERSION}"
    echo "=================================================="
    echo -e "${NC}"
}

# 显示使用说明
show_usage() {
    echo -e "${YELLOW}使用方法:${NC}"
    echo "  $0 install [版本号]    # 安装指定版本 (默认: latest)"
    echo "  $0 start               # 启动服务"
    echo "  $0 stop                # 停止服务"
    echo "  $0 restart             # 重启服务"
    echo "  $0 reset               # 重置服务（保留数据）"
    echo "  $0 status              # 查看服务状态"
    echo "  $0 logs [服务名]       # 查看日志"
    echo "  $0 diagnose            # 诊断服务状态"
    echo "  $0 update [版本号]     # 更新到指定版本"
    echo "  $0 uninstall           # 卸载服务"
    echo "  $0 --help              # 显示此帮助信息"
    echo ""
    echo -e "${YELLOW}示例:${NC}"
    echo "  $0 install             # 安装最新版本"
    echo "  $0 install v1.0.0      # 安装v1.0.0版本"
    echo "  $0 logs api            # 查看API服务日志"
    echo "  $0 diagnose            # 全面诊断系统状态"
    echo "  $0 reset               # 重置服务解决问题"
    echo ""
}

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_debug() {
    echo -e "${BLUE}[DEBUG]${NC} $1"
}

# 检查依赖
check_dependencies() {
    log_info "检查系统依赖..."
    
    # 检查Docker
    if ! command -v docker &> /dev/null; then
        log_error "Docker 未安装，请先安装 Docker"
        echo "安装指南: https://docs.docker.com/get-docker/"
        exit 1
    fi
    
    # 检查Docker Compose
    if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
        log_error "Docker Compose 未安装，请先安装 Docker Compose"
        echo "安装指南: https://docs.docker.com/compose/install/"
        exit 1
    fi
    
    # 检查Docker服务状态
    if ! docker info &> /dev/null; then
        log_error "Docker 服务未运行，请启动 Docker 服务"
        exit 1
    fi
    
    log_info "✅ 所有依赖检查完成"
}

# 获取最佳的 Docker Compose 命令
get_compose_cmd() {
    # 优先使用新版本的 docker compose
    if docker compose version &> /dev/null; then
        echo "docker compose"
    elif command -v docker-compose &> /dev/null; then
        echo "docker-compose"
    else
        log_error "未找到可用的 Docker Compose 命令"
        exit 1
    fi
}

# 构建版本化URL
build_versioned_url() {
    local version=$1
    local file_path=$2
    
    if [ "$version" = "latest" ]; then
        # 对于latest版本，使用main分支
        echo "${GITEE_BASE_URL}/raw/main/installer/${file_path}"
    else
        # 对于指定版本，使用release标签
        echo "${GITEE_BASE_URL}/raw/${version}/installer/${file_path}"
    fi
}

# 创建安装目录
create_install_dir() {
    log_info "创建安装目录: $INSTALL_DIR"
    mkdir -p "$INSTALL_DIR"
    mkdir -p "$INSTALL_DIR/logs"
}

# 下载环境变量文件
download_env_file() {
    log_info "下载环境变量文件..."
    
    if [ -f "$ENV_FILE" ]; then
        log_warn "✅ 环境变量文件已存在，跳过下载"
        return
    fi
    
    # 构建版本化URL
    local env_file_url=$(build_versioned_url "$version" ".env")
    
    # 检查是否有下载工具
    if ! command -v curl &> /dev/null && ! command -v wget &> /dev/null; then
        log_error "❌ 未找到下载工具 (curl 或 wget),请安装 curl 或 wget 后重试，或手动下载 .env 文件到: $ENV_FILE"
        exit 1
    fi
    
    # 尝试下载.env文件
    local download_success=false
    
    if command -v curl &> /dev/null; then
        if curl -fsSL "$env_file_url" -o "$ENV_FILE"; then
            download_success=true
        fi
    fi
    
    if [ "$download_success" = false ] && command -v wget &> /dev/null; then
        if wget -q "$env_file_url" -O "$ENV_FILE"; then
            download_success=true
        fi
    fi
    
    if [ "$download_success" = false ]; then
        log_error "❌ 无法下载环境变量文件, 下载地址: $env_file_url"
        log_error "可能的原因:"
        log_error "  1. 网络连接问题"
        log_error "  2. Gitee服务不可用"
        log_error "  3. 文件路径不存在"
        log_error ""
        log_error "请检查网络连接或手动下载 .env 文件到: $ENV_FILE"
        exit 1
    fi
    
    log_info "✅ 环境变量文件下载成功: $ENV_FILE"
    
    # 生成随机密码并替换到.env文件中
    log_info "生成随机密码并更新配置文件..."
    
    # 生成随机密码
    local POSTGRES_PASSWORD=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-25)
    local REDIS_PASSWORD=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-25)
    local NATS_PASSWORD=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-25)
    local S3_SECRET_KEY=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-25)
    local JWT_SECRET=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-25)
    ADMIN_PASSWORD=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-25)  # 移除local，使其成为全局变量
    local QDRANT_API_KEY=$(openssl rand -base64 32 | tr -d "=+/" | cut -c1-25)
    
    # 替换密码字段
    if command -v sed &> /dev/null; then
        # 使用sed替换密码
        sed -i "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=${POSTGRES_PASSWORD}/" "$ENV_FILE"
        sed -i "s/^REDIS_PASSWORD=.*/REDIS_PASSWORD=${REDIS_PASSWORD}/" "$ENV_FILE"
        sed -i "s/^NATS_PASSWORD=.*/NATS_PASSWORD=${NATS_PASSWORD}/" "$ENV_FILE"
        sed -i "s/^S3_SECRET_KEY=.*/S3_SECRET_KEY=${S3_SECRET_KEY}/" "$ENV_FILE"
        sed -i "s/^JWT_SECRET=.*/JWT_SECRET=${JWT_SECRET}/" "$ENV_FILE"
        sed -i "s/^ADMIN_PASSWORD=.*/ADMIN_PASSWORD=${ADMIN_PASSWORD}/" "$ENV_FILE"
        sed -i "s/^QDRANT_API_KEY=.*/QDRANT_API_KEY=${QDRANT_API_KEY}/" "$ENV_FILE"
    else
        log_warn "⚠️  sed命令未找到，无法自动更新密码"
        log_warn "请手动更新以下密码字段:"
        log_warn "  POSTGRES_PASSWORD=${POSTGRES_PASSWORD}"
        log_warn "  REDIS_PASSWORD=${REDIS_PASSWORD}"
        log_warn "  NATS_PASSWORD=${NATS_PASSWORD}"
        log_warn "  S3_SECRET_KEY=${S3_SECRET_KEY}"
        log_warn "  JWT_SECRET=${JWT_SECRET}"
        log_warn "  ADMIN_PASSWORD=${ADMIN_PASSWORD}"
        log_warn "  QDRANT_API_KEY=${QDRANT_API_KEY}"
    fi

}

# 清理冲突容器
cleanup_conflicting_containers() {
    log_info "检查并清理冲突容器..."
    

    # 检查是否有同名容器
    local conflicting_containers=(
        "sealog-wiki-caddy"
        "sealog-wiki-nginx"
        "sealog-wiki-app"
        "sealog-wiki-api"
        "sealog-wiki-consumer"
        "sealog-wiki-postgres"
        "sealog-wiki-redis"
        "sealog-wiki-minio"
        "sealog-wiki-nats"
        "sealog-wiki-qdrant"
        "sealog-wiki-crawler"
        "sealog-wiki-raglite"
    )
    local cleaned=false
    
    for container in "${containers[@]}"; do
        if docker ps -a --format "table {{.Names}}" | grep -q "^${container}$"; then
            log_warn "发现冲突容器: $container"
            if docker ps --format "table {{.Names}}" | grep -q "^${container}$"; then
                log_info "停止运行中的容器: $container"
                docker stop "$container" &> /dev/null || true
            fi
            log_info "删除容器: $container"
            docker rm "$container" &> /dev/null || true
            cleaned=true
        fi
    done
    
    if [ "$cleaned" = true ]; then
        log_info "✅ 冲突容器清理完成"
    else
        log_info "✅ 未发现冲突容器"
    fi
}

# 检查镜像仓库登录状态
check_registry_login() {
    local version=$1
    local registry="$DOCKER_REGISTRY"
    log_info "检查镜像仓库登录状态..."
    
    # 检查是否已登录
    if ! docker info 2>/dev/null | grep -q "Registry"; then
        log_warn "Docker 信息获取失败，尝试测试登录状态"
    fi
    
    # 尝试拉取一个小的测试镜像来验证登录状态
    local test_image="${registry}/seachartcode-server:${version}"
    if ! docker manifest inspect "$test_image" &> /dev/null; then
        log_warn "⚠️  似乎未登录到镜像仓库或没有访问权限"
        log_warn "请确保已经登录到华为云镜像仓库："
        echo "  docker login $registry"
        echo ""
        echo -e "${YELLOW}是否继续安装？(y/N): ${NC}"
        read -r continue_install
        if [[ ! "$continue_install" =~ ^[Yy]$ ]]; then
            log_error "安装已取消"
            exit 1
        fi
    else
        log_info "✅ 镜像仓库连接正常"
    fi
}

# 拉取Docker镜像
pull_images() {
    local version=$1
    log_info "拉取 Docker 镜像 (版本: $version)..."
    
    cd "$INSTALL_DIR"
    
    # 设置拉取超时
    export DOCKER_CLIENT_TIMEOUT=300
    export COMPOSE_HTTP_TIMEOUT=300
    
    # 使用最佳的 compose 命令拉取镜像，添加重试机制
    local compose_cmd=$(get_compose_cmd)
    local max_retries=3
    local retry_count=0
    
    while [ $retry_count -lt $max_retries ]; do
        log_info "尝试拉取镜像 (第 $((retry_count + 1)) 次)..."
        
        if $compose_cmd pull; then
            break
        fi
        
        retry_count=$((retry_count + 1))
        if [ $retry_count -lt $max_retries ]; then
            log_warn "镜像拉取失败，等待 10 秒后重试..."
            sleep 10
        fi
    done
    
    if [ $retry_count -eq $max_retries ]; then
        log_error "镜像拉取失败，已达到最大重试次数"
        log_error "请检查网络连接和镜像仓库登录状态"
        exit 1
    fi
    
    log_info "✅ Docker 镜像拉取完成"
}

# 安装服务
install_service() {
    local version=${1:-$DEFAULT_VERSION}
    VERSION=$version
    
    log_info "开始安装 SealogWiki (版本: $version)"
    
    check_dependencies
    cleanup_conflicting_containers
    create_install_dir
    download_env_file "$version"
    download_docker_compose "$version"
    check_registry_login "$version"
    pull_images "$version"
    
    log_info "✅ SealogWiki 安装完成！"
    echo ""
    echo -e "${GREEN}===========================================${NC}"
    echo -e "${GREEN}🎉 SealogWiki 安装成功！${NC}"
    echo -e "${GREEN}===========================================${NC}"
    echo ""
    echo -e "${YELLOW}下一步操作：${NC}"
    echo "  启动服务: $0 start"
    echo "  查看状态: $0 status"
    echo "  查看日志: $0 logs"
    echo ""
    echo -e "${YELLOW}配置文件位置：${NC}"
    echo "  安装目录: $INSTALL_DIR"
    echo "  环境配置: $ENV_FILE"
    echo "  服务配置: $COMPOSE_FILE"
    echo ""
}

show_access_info() {
    # 获取本机IP地址
    local host_ip=$(hostname -I | awk '{print $1}')
    # 从 .env 文件读取 ADMIN_PORT
    local admin_port="30388"  # 默认值
    local admin_password=""

    if [ -f ".env" ]; then
        local env_port=$(grep "^ADMIN_PORT=" .env | cut -d'=' -f2)
        if [ -n "$env_port" ]; then
            admin_port="$env_port"
        fi
        # 从 .env 文件读取管理员密码
        admin_password=$(grep "^ADMIN_PASSWORD=" .env | cut -d'=' -f2)
    else
        log_info ".env 文件不存在"
    fi

    echo "管理员用户名: admin"
    if [ -n "$admin_password" ]; then
        echo "管理员密码: $admin_password"
    else
        echo "管理员密码: 未设置或无法读取"
    fi
    echo "访问地址: https://$host_ip:$admin_port"
    echo "工作目录: ${INSTALL_DIR}"
}

# 启动服务
start_service() {
    if [ ! -f "$COMPOSE_FILE" ]; then
        log_error "服务未安装，请先运行: $0 install"
        exit 1
    fi
    
    log_info "启动 SealogWiki 服务..."
    
    # 清理可能存在的冲突容器
    cleanup_conflicting_containers
    
    cd "$INSTALL_DIR"
    
    # 尝试启动服务，添加错误处理
    local compose_cmd=$(get_compose_cmd)
    local start_success=false
    if $compose_cmd up -d; then
        start_success=true
    fi
    
    if [ "$start_success" = false ]; then
        log_error "服务启动失败"
        log_info "正在查看错误日志..."
        $compose_cmd logs --tail=50
        exit 1
    fi
    
    log_info "⏳ 等待服务启动..."
    
    # 等待服务健康检查
    local max_wait=60
    local wait_count=0
    local all_healthy=false
    
    while [ $wait_count -lt $max_wait ] && [ "$all_healthy" = false ]; do
        sleep 5
        wait_count=$((wait_count + 5))
        
        # 检查容器健康状态
        local unhealthy_count=0
        unhealthy_count=$($compose_cmd ps | grep -E "(unhealthy|starting)" | wc -l)
        
        if [ "$unhealthy_count" -eq 0 ]; then
            all_healthy=true
        else
            log_info "等待服务健康检查... (${wait_count}s/${max_wait}s)"
        fi
    done
    
    if [ "$all_healthy" = false ]; then
        log_warn "⚠️  某些服务可能未完全启动，请检查服务状态"
    fi
    
    # 检查服务状态
    show_status
    
    # 显示访问信息
    show_access_info
}


# 停止服务
stop_service() {
    if [ ! -f "$COMPOSE_FILE" ]; then
        log_error "服务未安装"
        exit 1
    fi
    
    log_info "停止 SealogWiki 服务..."
    cd "$INSTALL_DIR"
    
    local compose_cmd=$(get_compose_cmd)
    $compose_cmd down
    
    log_info "✅ SealogWiki 服务已停止"
}

# 重启服务
restart_service() {
    log_info "重启 SealogWiki 服务..."
    stop_service
    sleep 2
    start_service
}

# 下载并配置docker-compose.yml文件
download_docker_compose() {
    local version=$1
    log_info "下载docker-compose.yml文件..."
    local compose_file_url=$(build_versioned_url "$version" "docker-compose.yml")
    local temp_compose_file="/tmp/docker-compose.yml.tmp"
    
    # 下载docker-compose.yml文件
    local download_success=false
    
    if command -v curl &> /dev/null; then
        if curl -fsSL "$compose_file_url" -o "$temp_compose_file"; then
            download_success=true
        fi
    fi
    
    if [ "$download_success" = false ] && command -v wget &> /dev/null; then
        if wget -q "$compose_file_url" -O "$temp_compose_file"; then
            download_success=true
        fi
    fi
    
    if [ "$download_success" = false ]; then
        log_error "❌ 无法下载docker-compose.yml文件, 下载地址: $compose_file_url"
        exit 1
    fi
    
    log_info "✅ docker-compose.yml文件下载成功"
    
    # 配置镜像地址和版本
    log_info "配置镜像地址和版本..."
    
    # 设置默认的Docker镜像仓库
    local DOCKER_REGISTRY=${DOCKER_REGISTRY:-"swr.cn-east-3.myhuaweicloud.com/cloud-mdgx/sealog"}
    local VERSION=${version:-"latest"}
    
    # 替换镜像配置
    if command -v sed &> /dev/null; then
        # 替换 sealog-wiki-app 镜像
        sed -i "s|image: .*/sealog-wiki-app:.*|image: ${DOCKER_REGISTRY}/sealog-wiki-app:${VERSION}|" "$temp_compose_file"

        # 替换 sealog-wiki-api 镜像
        sed -i "s|image: .*/sealog-wiki-api:.*|image: ${DOCKER_REGISTRY}/sealog-wiki-api:${VERSION}|" "$temp_compose_file"
        # 替换 sealog-wiki-nginx 镜像
        sed -i "s|image: .*/sealog-wiki-nginx:.*|image: ${DOCKER_REGISTRY}/sealog-wiki-nginx:${VERSION}|" "$temp_compose_file"

        # 替换 sealog-wiki-consumer 镜像
        sed -i "s|image: .*/sealog-wiki-consumer:.*|image: ${DOCKER_REGISTRY}/sealog-wiki-consumer:${VERSION}|" "$temp_compose_file"
        # 替换 sealog-wiki-postgres 镜像
        sed -i "s|image: .*/sealog-wiki-postgres:.*|image: ${DOCKER_REGISTRY}/sealog-wiki-postgres:${VERSION}|" "$temp_compose_file"
        # 替换 sealog-wiki-redis 镜像
        sed -i "s|image: .*/sealog-wiki-redis:.*|image: ${DOCKER_REGISTRY}/sealog-wiki-redis:${VERSION}|" "$temp_compose_file"
        # 替换 sealog-wiki-minio 镜像
        sed -i "s|image: .*/sealog-wiki-minio:.*|image: ${DOCKER_REGISTRY}/sealog-wiki-minio:${VERSION}|" "$temp_compose_file"
        # 替换 sealog-wiki-nats 镜像
        sed -i "s|image: .*/sealog-wiki-nats:.*|image: ${DOCKER_REGISTRY}/sealog-wiki-nats:${VERSION}|" "$temp_compose_file"
        # 替换 sealog-wiki-qdrant 镜像
        sed -i "s|image: .*/sealog-wiki-qdrant:.*|image: ${DOCKER_REGISTRY}/sealog-wiki-qdrant:${VERSION}|" "$temp_compose_file"
        # 替换 sealog-wiki-crawler 镜像
        sed -i "s|image: .*/sealog-wiki-crawler:.*|image: ${DOCKER_REGISTRY}/sealog-wiki-crawler:${VERSION}|" "$temp_compose_file"
        # 替换 sealog-wiki-raglite 镜像
        sed -i "s|image: .*/sealog-wiki-raglite:.*|image: ${DOCKER_REGISTRY}/sealog-wiki-raglite:${VERSION}|" "$temp_compose_file"
        # 替换 sealog-wiki-caddy 镜像
        sed -i "s|image: .*/sealog-wiki-caddy:.*|image: ${DOCKER_REGISTRY}/sealog-wiki-caddy:${VERSION}|" "$temp_compose_file"
        log_info "✅ 镜像配置已更新"
    else
        log_warn "⚠️  sed命令未找到，无法自动更新镜像配置"
        log_warn "请手动更新以下镜像配置:"
        log_warn "  sealog-wiki-app: ${DOCKER_REGISTRY}/sealog-wiki-app:${VERSION}"
        log_warn "  sealog-wiki-api: ${DOCKER_REGISTRY}/sealog-wiki-api:${VERSION}"
        log_warn "  sealog-wiki-nginx: ${DOCKER_REGISTRY}/sealog-wiki-nginx:${VERSION}"
        log_warn "  sealog-wiki-consumer: ${DOCKER_REGISTRY}/sealog-wiki-consumer:${VERSION}"
        log_warn "  sealog-wiki-postgres: ${DOCKER_REGISTRY}/sealog-wiki-postgres:${VERSION}"
        log_warn "  sealog-wiki-redis: ${DOCKER_REGISTRY}/sealog-wiki-redis:${VERSION}"
        log_warn "  sealog-wiki-minio: ${DOCKER_REGISTRY}/sealog-wiki-minio:${VERSION}"
        log_warn "  sealog-wiki-nats: ${DOCKER_REGISTRY}/sealog-wiki-nats:${VERSION}"
        log_warn "  sealog-wiki-qdrant: ${DOCKER_REGISTRY}/sealog-wiki-qdrant:${VERSION}"
        log_warn "  sealog-wiki-crawler: ${DOCKER_REGISTRY}/sealog-wiki-crawler:${VERSION}"
        log_warn "  sealog-wiki-raglite: ${DOCKER_REGISTRY}/sealog-wiki-raglite:${VERSION}"
        log_warn "  sealog-wiki-caddy: ${DOCKER_REGISTRY}/sealog-wiki-caddy:${VERSION}"
    fi
    
    # 移动文件到目标位置
    mv "$temp_compose_file" "$COMPOSE_FILE"
    log_info "✅ docker-compose.yml文件已配置完成: $COMPOSE_FILE"
}

# 查看服务日志
show_logs() {
    local service_name=$1
    
    if [ ! -f "$COMPOSE_FILE" ]; then
        log_error "服务未安装"
        exit 1
    fi
    
    cd "$INSTALL_DIR"
    
    local compose_cmd=$(get_compose_cmd)
    
    if [ -n "$service_name" ]; then
        log_info "查看服务 $service_name 的日志..."
        $compose_cmd logs --tail=100 -f "$service_name"
    else
        log_info "查看所有服务的日志..."
        $compose_cmd logs --tail=100 -f
    fi
}

# 查看服务状态
show_status() {
    if [ ! -f "$COMPOSE_FILE" ]; then
        log_error "服务未安装"
        exit 1
    fi
    
    cd "$INSTALL_DIR"
    
    echo -e "${CYAN}======================= 服务状态 =======================${NC}"
    local compose_cmd=$(get_compose_cmd)
    $compose_cmd ps
    echo -e "${CYAN}=======================================================${NC}"
}

# 更新服务
update_service() {
    local version=${1:-$DEFAULT_VERSION}
    
    log_info "更新 SealogWiki 到版本: $version"
    
    # 备份当前环境变量
    if [ -f "$ENV_FILE" ]; then
        cp "$ENV_FILE" "$ENV_FILE.backup"
        log_info "已备份环境变量文件"
    fi
    
    # 备份数据目录（如果存在）
    if [ -d "$INSTALL_DIR/data" ]; then
        log_info "发现数据目录，将在更新后保留: $INSTALL_DIR/data"
        log_info "您的知识库数据将被安全保留"
    fi
    
    # 停止当前服务
    if [ -f "$COMPOSE_FILE" ]; then
        stop_service
    fi
    
    # 重新下载配置文件
    download_env_file "$version"
    download_docker_compose "$version"
    
    # 拉取新镜像
    pull_images "$version"
    
    # 启动服务
    start_service
    
    log_info "✅ SealogWiki 更新完成！"
    if [ -d "$INSTALL_DIR/data" ]; then
        log_info "✅ 您的知识库数据已安全保留在: $INSTALL_DIR/data"
    fi
}

# 重置服务（保留数据）
reset_service() {
    log_info "重置 SealogWiki 服务（保留数据）..."
    
    # 停止服务
    if [ -f "$COMPOSE_FILE" ]; then
        stop_service
    fi
    
    # 清理容器但保留数据卷
    cleanup_conflicting_containers
    
    # 重新启动
    start_service
    
    log_info "✅ SealogWiki 服务重置完成！"
}

# 诊断服务状态
diagnose_service() {
    log_info "开始诊断 SealogWiki 服务状态..."
    echo ""
    
    # 检查Docker
    echo -e "${CYAN}=== Docker 状态 ===${NC}"
    if docker info &> /dev/null; then
        echo "✅ Docker 服务正常"
    else
        echo "❌ Docker 服务异常"
    fi
    echo ""
    
    # 检查安装
    echo -e "${CYAN}=== 安装状态 ===${NC}"
    if [ -f "$COMPOSE_FILE" ]; then
        echo "✅ Docker Compose 文件存在: $COMPOSE_FILE"
    else
        echo "❌ Docker Compose 文件不存在"
    fi
    
    if [ -f "$ENV_FILE" ]; then
        echo "✅ 环境配置文件存在: $ENV_FILE"
    else
        echo "❌ 环境配置文件不存在"
    fi
    echo ""
    
    # 检查容器状态
    if [ -f "$COMPOSE_FILE" ]; then
        echo -e "${CYAN}=== 容器状态 ===${NC}"
        cd "$INSTALL_DIR"
        local compose_cmd=$(get_compose_cmd)
        $compose_cmd ps
        echo ""
        
        # 检查健康状态
        echo -e "${CYAN}=== 健康检查 ===${NC}"

        local containers=(
            "sealog-wiki-caddy"
            "sealog-wiki-nginx"
            "sealog-wiki-app"
            "sealog-wiki-api"
            "sealog-wiki-consumer"
            "sealog-wiki-postgres"
            "sealog-wiki-redis"
            "sealog-wiki-minio"
            "sealog-wiki-nats"
            "sealog-wiki-qdrant"
            "sealog-wiki-crawler"
            "sealog-wiki-raglite"
        )
        for container in "${containers[@]}"; do
            if docker ps --format "table {{.Names}}\t{{.Status}}" | grep -q "$container"; then
                local status=$(docker ps --format "table {{.Names}}\t{{.Status}}" | grep "$container" | awk '{print $2}')
                if [[ "$status" == *"healthy"* ]]; then
                    echo "✅ $container: 健康"
                elif [[ "$status" == *"unhealthy"* ]]; then
                    echo "❌ $container: 不健康"
                else
                    echo "⏳ $container: $status"
                fi
            else
                echo "❌ $container: 未运行"
            fi
        done
        echo ""
    fi
    
    # 检查镜像
    echo -e "${CYAN}=== 镜像状态 ===${NC}"
    local found_images=false
    local target_images=(
        "${DOCKER_REGISTRY}/sealog-wiki-caddy"
        "${DOCKER_REGISTRY}/sealog-wiki-nginx"
        "${DOCKER_REGISTRY}/sealog-wiki-app"
        "${DOCKER_REGISTRY}/sealog-wiki-api"
        "${DOCKER_REGISTRY}/sealog-wiki-consumer"
        "${DOCKER_REGISTRY}/sealog-wiki-postgres"
        "${DOCKER_REGISTRY}/sealog-wiki-redis"
        "${DOCKER_REGISTRY}/sealog-wiki-minio"
        "${DOCKER_REGISTRY}/sealog-wiki-nats"
        "${DOCKER_REGISTRY}/sealog-wiki-qdrant"
        "${DOCKER_REGISTRY}/sealog-wiki-crawler"
        "${DOCKER_REGISTRY}/sealog-wiki-raglite"
    )
    
    # 收集所有镜像信息
    local all_images=""
    for image_repo in "${target_images[@]}"; do
        local images=$(docker images --format "{{.Repository}}\t{{.Tag}}\t{{.Size}}" | grep "^${image_repo}" || true)
        if [ -n "$images" ]; then
            if [ "$found_images" = false ]; then
                all_images="Repository\tTag\tSize\n"
                found_images=true
            fi
            all_images="${all_images}${images}\n"
        fi
    done
    
    # 使用 column 命令自动对齐输出，如果没有 column 命令则使用 printf
    if [ -n "$all_images" ]; then
        if command -v column &> /dev/null; then
            echo -e "$all_images" | column -t -s $'\t'
        else
            # 备选方案：使用 printf 手动对齐
            echo -e "$all_images" | while IFS=$'\t' read -r repo tag size; do
                if [ "$repo" = "Repository" ]; then
                    printf "%-60s %-20s %-15s\n" "$repo" "$tag" "$size"
                else
                    printf "%-60s %-20s %-15s\n" "$repo" "$tag" "$size"
                fi
            done
        fi
    fi
    
    if [ "$found_images" = false ]; then
        echo "未找到相关镜像"
    fi
    echo ""
    
    # 检查磁盘空间
    echo -e "${CYAN}=== 磁盘空间 ===${NC}"
    df -h "$INSTALL_DIR" 2>/dev/null || df -h /
    echo ""
    
    log_info "诊断完成"
}

# 卸载服务
uninstall_service() {
    log_info "开始卸载 SealogWiki..."
    
    # 停止并删除容器
    if [ -f "$COMPOSE_FILE" ]; then
        cd "$INSTALL_DIR"
        log_info "停止并删除容器..."
        echo -e "${YELLOW}是否继续删除容器？(yes/no): ${NC}"
        read -r user_confirm
        if [[ "$user_confirm" == "yes" ]]; then
            local compose_cmd=$(get_compose_cmd)
            $compose_cmd down -v --remove-orphans
            log_info "✅ 容器已删除"
        else
            log_info "ℹ️  跳过容器删除"
        fi
    fi

     # 删除网络（如果存在）
    log_info "清理网络..."
    if docker network ls --format "{{.Name}}" | grep -q "^sealog-wiki$"; then
        echo -e "${YELLOW}是否删除网络 sealog-wiki？(yes/no): ${NC}"
        read -r user_confirm
        if [[ "$user_confirm" == "yes" ]]; then
            docker network rm sealog-wiki
            log_info "✅ 网络 sealog-wiki 已删除"
        else
            log_info "ℹ️  跳过网络删除"
        fi
    else
        log_info "ℹ️  网络 sealog-wiki 不存在，跳过删除"
    fi
    
    # 删除镜像
    log_info "删除相关镜像..."
    local images_to_remove=(
        "${DOCKER_REGISTRY}/sealog-wiki-caddy"
        "${DOCKER_REGISTRY}/sealog-wiki-nginx"
        "${DOCKER_REGISTRY}/sealog-wiki-app"
        "${DOCKER_REGISTRY}/sealog-wiki-api"
        "${DOCKER_REGISTRY}/sealog-wiki-consumer"
        "${DOCKER_REGISTRY}/sealog-wiki-postgres"
        "${DOCKER_REGISTRY}/sealog-wiki-redis"
        "${DOCKER_REGISTRY}/sealog-wiki-minio"
        "${DOCKER_REGISTRY}/sealog-wiki-nats"
        "${DOCKER_REGISTRY}/sealog-wiki-qdrant"
        "${DOCKER_REGISTRY}/sealog-wiki-crawler"
        "${DOCKER_REGISTRY}/sealog-wiki-raglite"
    )
    
    # 检查有哪些镜像存在
    local existing_images=()
    for image_repo in "${images_to_remove[@]}"; do
        local image_tags=$(docker images --format "{{.Repository}}:{{.Tag}}" | grep "^${image_repo}:" || true)
        if [ -n "$image_tags" ]; then
            existing_images+=("$image_repo")
        fi
    done
    
    if [ ${#existing_images[@]} -gt 0 ]; then
        log_info "发现以下镜像:"
        for img in "${existing_images[@]}"; do
            echo "  - $img"
        done
        
        echo -e "${YELLOW}是否删除所有相关镜像？(yes/no): ${NC}"
        read -r user_confirm
        if [[ "$user_confirm" == "yes" ]]; then
            local deleted_count=0
            for image_repo in "${existing_images[@]}"; do
                local image_tags=$(docker images --format "{{.Repository}}:{{.Tag}}" | grep "^${image_repo}:" || true)
                if echo "$image_tags" | xargs -r docker rmi 2>/dev/null; then
                    deleted_count=$((deleted_count + 1))
                    log_info "✅ 镜像 $image_repo 已删除"
                else
                    log_warn "⚠️  删除镜像 $image_repo 时出现警告，继续执行"
                fi
            done
            log_info "✅ 成功删除 $deleted_count 个镜像"
        else
            log_info "ℹ️  跳过镜像删除"
        fi
    else
        log_info "ℹ️  没有发现相关镜像，跳过删除"
    fi

    if [ $deleted_count -gt 0 ]; then
        log_info "✅ 成功删除 $deleted_count 个镜像"
    fi
    
    # 删除安装目录
    log_info "删除安装目录..."
    if [ -d "$INSTALL_DIR" ]; then
        # 特别提示数据目录的重要性
        if [ -d "$INSTALL_DIR/data" ]; then
            echo ""
            echo -e "${RED}⚠️  重要提醒：${NC}"
            echo -e "${RED}安装目录 $INSTALL_DIR 包含您的知识库数据！${NC}"
            echo -e "${RED}数据目录: $INSTALL_DIR/data${NC}"
            echo -e "${RED}删除后将无法恢复，请确保已备份重要数据！${NC}"
            echo ""
        fi
        
        echo -e "${YELLOW}是否删除安装目录 $INSTALL_DIR？(yes/no): ${NC}"
        read -r user_confirm
        if [[ "$user_confirm" == "yes" ]]; then
            log_info "正在删除安装目录..."
            
            # 尝试删除安装目录
            if rm -rf "$INSTALL_DIR" 2>/tmp/sealog_rm_error.log; then
                log_info "✅ 安装目录已删除: $INSTALL_DIR"
                if [ -d "$INSTALL_DIR/data" ]; then
                    log_warn "⚠️  您的知识库数据已被删除！"
                fi
            else
                # 检查删除失败的原因
                local rm_error=$(cat /tmp/sealog_rm_error.log 2>/dev/null || echo "未知错误")
                rm -f /tmp/sealog_rm_error.log 2>/dev/null
                
                echo ""
                echo -e "${RED}❌ 删除安装目录失败！${NC}"
                echo -e "${RED}错误信息: $rm_error${NC}"
                echo ""
                echo -e "${YELLOW}可能的原因：${NC}"
                echo "  • 权限不足（需要管理员权限）"
                echo "  • 文件被其他进程占用"
                echo "  • 磁盘空间不足"
                echo "  • 文件系统只读"
                echo ""
                echo -e "${YELLOW}建议操作：${NC}"
                echo "  1. 检查权限：sudo ls -la $INSTALL_DIR"
                echo "  2. 手动删除：sudo rm -rf $INSTALL_DIR"
                echo "  3. 检查进程：lsof | grep $INSTALL_DIR"
                echo "  4. 检查磁盘：df -h"
                echo ""
                echo -e "${CYAN}是否继续卸载流程？(yes/no): ${NC}"
                read -r continue_uninstall
                if [[ "$continue_uninstall" != "yes" ]]; then
                    log_info "ℹ️  用户取消卸载，请手动删除安装目录后重新运行卸载命令"
                    exit 0
                fi
            fi
        else
            log_info "ℹ️  跳过安装目录删除"
        fi
    else
        log_info "ℹ️  安装目录不存在，跳过删除"
    fi
    
    echo ""
    echo -e "${GREEN}===========================================${NC}"
        echo -e "${GREEN}🗑️  SealogWiki 卸载完成！${NC}"
    echo -e "${GREEN}===========================================${NC}"
    echo ""
    log_info "感谢使用 SealogWiki！"
}

# 主函数
main() {
    show_banner
    
    case "${1:-}" in
        "install")
            install_service "$2"
            ;;
        "start")
            start_service
            ;;
        "stop")
            stop_service
            ;;
        "restart")
            restart_service
            ;;
        "reset")
            reset_service
            ;;
        "status")
            show_status
            ;;
        "logs")
            show_logs "$2"
            ;;
        "diagnose")
            diagnose_service
            ;;
        "update")
            update_service "$2"
            ;;
        "uninstall")
            uninstall_service
            ;;
        "--help"|"-h"|"help")
            show_usage
            ;;
        "")
            log_error "缺少操作参数"
            echo ""
            show_usage
            exit 1
            ;;
        *)
            log_error "未知操作: $1"
            echo ""
            show_usage
            exit 1
            ;;
    esac
}

# 执行主函数
main "$@"
